/*
 * This file is part of jboss-admin-rest
 * Copyright 2009, Christos Vasilakis (cvasilak@gmail.com)
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.admin.rest.services;

import org.jboss.admin.rest.domain.ComponentsContainer;
import org.jboss.admin.rest.domain.deployments.OperationBean;
import org.jboss.admin.rest.exceptions.BadRequestException;
import org.jboss.admin.rest.exceptions.InternalServerErrorException;
import org.jboss.admin.rest.factory.ProfileServiceFactory;
import org.jboss.admin.rest.util.ManagedComponentUtils;
import org.jboss.deployers.spi.management.KnownComponentTypes;
import org.jboss.deployers.spi.management.ManagementView;
import org.jboss.managed.api.ComponentType;
import org.jboss.managed.api.ManagedComponent;
import org.jboss.profileservice.spi.NoSuchDeploymentException;
import org.jboss.resteasy.annotations.providers.jaxb.Formatted;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.util.HashSet;
import java.util.Set;

@Produces( {"application/xml", "application/json"} )  
public class ComponentResource extends BaseResource {

	@GET
	@Formatted
	public ComponentsContainer getComponentsList() throws BadRequestException, NoSuchDeploymentException, InternalServerErrorException {
		return (ComponentsContainer) getComponent(ANY, null, null);
	}

	@POST
	@Consumes("multipart/form-data")
	public Response uploadComponent(@Context HttpServletRequest request) throws BadRequestException, InternalServerErrorException {
		return super.uploadArtifact(request);
	}

	@GET
	@Path("/{type}")
	@Formatted
	public ComponentsContainer getComponentsList(@PathParam("type") String type) throws BadRequestException, NoSuchDeploymentException, InternalServerErrorException {
		return (ComponentsContainer) getComponent(type, null, null);
	}

	@GET
	@Path("/{type}/{subtype}")
	@Formatted
	public Object getComponent(@PathParam("type") String type, @PathParam("subtype") String subtype, @QueryParam("name") String name) throws BadRequestException, NoSuchDeploymentException, InternalServerErrorException {
		if (name == null) {
			ComponentsContainer list = new ComponentsContainer();
			list.add(getManagedComponents(type, subtype));
			return list;

		} else {
			return ManagedComponentUtils.getWrappedComponentBean(getManagedComponent(type, subtype, name));
		}
	}

	@PUT
	@Path("/{type}/{subtype}")
	public Response updateComponent(@PathParam("type") String type, @PathParam("subtype") String subtype, @QueryParam("name") String name, OperationBean operation) throws BadRequestException, NoSuchDeploymentException, InternalServerErrorException {
		return super.updateArtifact(getManagedComponent(type, subtype, name).getDeployment().getSimpleName(), operation);
	}

	@DELETE
	@Path("/{type}/{subtype}")
	public Response undeployComponent(@PathParam("type") String type, @PathParam("subtype") String subtype, @QueryParam("name") String name) throws NoSuchDeploymentException, InternalServerErrorException {
		return super.undeployArtifact(getManagedComponent(type, subtype, name).getDeployment().getSimpleName());
	}

	private ManagedComponent getManagedComponent(String type, String subtype, String name) throws NoSuchDeploymentException, InternalServerErrorException {
		ManagedComponent match = null;

		try {
			ManagementView mv = ProfileServiceFactory.getCurrentManagementView();
			match = mv.getComponent(name, new ComponentType(type, subtype));

		} catch (Exception e) {
			throw new InternalServerErrorException(e.getMessage(), e);
		}

		if (match == null) {
			throw new NoSuchDeploymentException(name);
		}

		return match;
	}

	private Set<ManagedComponent> getManagedComponents(String type, String subtype) throws BadRequestException, InternalServerErrorException {
		ManagementView mv = ProfileServiceFactory.getCurrentManagementView();

		Set<ManagedComponent> components;

        try {
            if (subtype != null) {
                components = mv.getComponentsForType(new ComponentType(type, subtype));

                /*
                 * TODO
                 * check if type or subtype is valid and throw BadRequestException
                 */
            } else {
                if (type.equals(ANY)) {
                    components = mv.getComponentsForType(KnownComponentTypes.ANY_TYPE);
                } else {
                    components = new HashSet<ManagedComponent>();

                    if (type.equals("DataSource")) {
                        for (KnownComponentTypes.DataSourceTypes t : KnownComponentTypes.DataSourceTypes.values()) {
                            components.addAll(mv.getComponentsForType(t.getType()));
                        }
                    } else if (type.equals("ConnectionFactory")) {
                        for (KnownComponentTypes.ConnectionFactoryTypes t : KnownComponentTypes.ConnectionFactoryTypes.values()) {
                            components.addAll(mv.getComponentsForType(t.getType()));
                        }
                    } else if (type.equals("JMSDestination")) {
                        for (KnownComponentTypes.JMSDestination t : KnownComponentTypes.JMSDestination.values()) {
                            components.addAll(mv.getComponentsForType(t.getType()));
                        }
                    } else if (type.equals("MBean")) {
                        for (KnownComponentTypes.MBean t : KnownComponentTypes.MBean.values()) {
                            components.addAll(mv.getComponentsForType(t.getType()));
                        }
                    } else if (type.equals("MCBean")) {
                        for (KnownComponentTypes.MCBean t : KnownComponentTypes.MCBean.values()) {
                            components.addAll(mv.getComponentsForType(t.getType()));
                        }
                    } else {
                        throw new BadRequestException("component type specified unknown!");
                    }
                }
            }
        } catch (Exception e) {
            throw new InternalServerErrorException(e.getMessage(), e);
        }

		return components;
	}
}
